/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.pc9.pswing.components.filebrowser;

import br.com.pc9.pswing.util.SystemUtilsOS;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author paulocanedo
 */
public class FileNavigationComboBoxModel extends DefaultComboBoxModel {

    private PFileView currentFolder;
    private List<PFileView> currentFileView = new ArrayList<PFileView>();

    public FileNavigationComboBoxModel() {
        currentFolder = new PFileView(SystemUtilsOS.getUserHomeAsFile());

        setFolderView(currentFolder);
    }

    private void setFolderView(PFileView folder) {
        currentFileView.clear();
        
        this.currentFolder = folder;
        currentFileView.add(folder);

        File file = folder.getFile();
        while ((file = file.getParentFile()) != null) {
            currentFileView.add(new PFileView(file));
        }
    }

    private void fireDataChanged(int oldSize, int newSize) {
        if (oldSize > 0) {
            fireIntervalRemoved(this, 0, oldSize);
        }

        if (newSize > 0) {
            fireIntervalAdded(this, 0, newSize);
            setSelectedItem(currentFolder);
        }
    }

    public void open(File folder) {
        int oldSize = currentFileView.size();
        setFolderView(new PFileView(folder));

        fireDataChanged(oldSize, currentFileView.size());
    }

    @Override
    public Object getElementAt(int index) {
        return currentFileView.get(index);
    }

    @Override
    public int getSize() {
        return currentFileView.size();
    }

    @Override
    public void setSelectedItem(Object anItem) {
        this.currentFolder = (PFileView) anItem;
        fireContentsChanged(this, -1, -1);
    }

    @Override
    public PFileView getSelectedItem() {
        return currentFolder;
    }

}
